package z.sample.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import z.sample.persistence.dao.CustomerDao;
import z.sample.persistence.dao.EmployeeDao;
import z.sample.persistence.dao.OfficeDao;
import z.sample.persistence.entity.Customer;
import z.sample.persistence.entity.Employee;
import z.sample.persistence.entity.Office;

@Service
public class DemoServiceImpl implements DemoService {
	@Autowired
	private CustomerDao customerDao;
	
	@Autowired
	private OfficeDao officeDao;
	
	@Autowired
	private EmployeeDao employeeDao;
	
	@Override
	public List<Customer> getAllCustomers() {
		return this.customerDao.findAll();
	}
	
	@Override
	public List<Customer> findCustomersByName(final String name) {
		return this.customerDao.findByName(name);
	}

	@Override
	public List<Employee> getAllEmployees() {
		return this.employeeDao.findAll();
	}

	@Override
	public List<Office> getAllOffices() {
		return this.officeDao.findAll();
	}
	
	public List<Customer> getCustomerOfAReporter(final Long reporterId) {
		List<Customer> listCustomers = new ArrayList<Customer>();
		listCustomers = this.customerDao.findAll(new Specification<Customer>() {
			@Override
			public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query,
					CriteriaBuilder cb) {
				Subquery<Employee> subQuery = query.subquery(Employee.class);
				Root<Employee> fromEmployee = subQuery.from(Employee.class);
				subQuery.select(fromEmployee);
				Predicate p = cb.equal(fromEmployee.get("reportTo"), reporterId);
				subQuery.where(p);
				return cb.in(root.get("employee")).value(subQuery);
			}
		});
		return listCustomers;
	}

}
